#include "loginlogmanager.h"

LoginLogManager::LoginLogManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_loginLog_hideSearch->setIcon(pix);
    ui->btn_loginLog_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_loginLog_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_loginLog_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget_loginLog->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_loginLog->setSelectionBehavior(QAbstractItemView::SelectRows);

    init();

    //隐藏搜索
    connect(ui->btn_loginLog_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_82->setHidden(!ui->widget_82->isHidden());
    });
    // 下一页
    connect(ui->btn_loginLog_next,&QPushButton::clicked,this,[=](){
        ui->btn_loginLog_next->setEnabled(0);
        currentPage ++;
        getList();
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_loginLog_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_loginLog_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_loginLog_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_loginLog_gotoPage->text().toInt();
        ui->lineEdit_loginLog_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_loginLog_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_loginLog_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTable();
        initPageInfo();
    });
    //    每页大小
    connect(ui->comboBox_loginLog_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //    重置
    connect(ui->btn_loginLog_reset,&QPushButton::clicked,this,[=](){
        ui->btn_loginLog_reset->setEnabled(0);
        init();
        ui->btn_loginLog_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_loginLog_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_loginLog_refresh,&QPushButton::clicked,this,[=](){
        ui->btn_loginLog_refresh->setEnabled(0);
        getList();
        initTable();
        initPageInfo();
        ui->btn_loginLog_refresh->setEnabled(1);
    });
    connect(ui->btn_loginLog_clear,&QPushButton::clicked,this,[=](){
        int flag = QMessageBox::question(0,"提示","是否确认清空所有操作日志数据项?",QMessageBox::Yes|QMessageBox::No);
        if(flag == QMessageBox::No) return;
        QByteArray *bytes = api.clear();
        QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
        if(200 == obj.value("code").toInt()){
            QMessageBox::warning(0,"提示",obj.value("msg").toString());
            getList();
            initTable();
            initPageInfo();
        }
    });
    connect(ui->btn_loginLog_unlock,&QPushButton::clicked,this,[=](){
        QList<QTableWidgetItem*> items = ui->tableWidget_loginLog->selectedItems();
        if(items.size() == 0) return;
        int rowCount = items.size() / 8;    //选中的行数
        if(rowCount > 1) return;
        int index = ui->tableWidget_loginLog->row(items.at(0));
        QString userName = ui->tableWidget_loginLog->item(index,1)->text();
        int flag = QMessageBox::question(0,"提示","是否解锁用户[" + userName + "]数据项?",QMessageBox::Yes|QMessageBox::No);
        if(flag == QMessageBox::No) return;
        QByteArray *bytes = api.unlock(userName);
        QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
        if(200 == obj.value("code").toInt()){
            QMessageBox::warning(0,"提示",obj.value("msg").toString());
            getList();
            initTable();
            initPageInfo();
        }
    });
    //批量删除
    connect(ui->btn_loginLog_del,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_loginLog_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget_loginLog,"登录日志表格");
    });
}

void LoginLogManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}

void LoginLogManager::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_loginLog->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 8;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_loginLog->row(items.at(i * 8));
        if(i != rowCount - 1){
            ids += ui->tableWidget_loginLog->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_loginLog->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = api.deleteItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}

void LoginLogManager::init()
{
    getType();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void LoginLogManager::getType()
{
    sys_common_status.clear();
    QByteArray *data = utils.getDictType("sys_common_status");
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        sys_common_status.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void LoginLogManager::initSearchArea()
{
    ui->lineEdit_loginLog_loginLocation->clear();
    ui->lineEdit_loginLog_userName->clear();
    ui->comboBox_loginLog_status->clear();
    ui->comboBox_loginLog_status->addItem("");
    for(int i = 0;i< sys_common_status.size();i++){
        ui->comboBox_loginLog_status->addItem(sys_common_status.at(i).dictLabel,sys_common_status.at(i).dictValue);
    }
    ui->dateEdit_loginLog_start->setDate(QDate(2000,1,1));
    ui->dateEdit_loginLog_end->setDate(QDate(2000,1,1));
}

void LoginLogManager::getList()
{
    logList.clear();
    QString loginLocation = ui->lineEdit_loginLog_loginLocation->text();
    QString userName = ui->lineEdit_loginLog_userName->text();
    QString status = ui->comboBox_loginLog_status->currentData().value<QString>();
    QString start = ui->dateEdit_loginLog_start->text();
    QString end = ui->dateEdit_loginLog_end->text();
    QByteArray *data = api.list(currentPage,pageSize,loginLocation,userName,status,start,end);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        logList.append(LoginInfo::toLoginInfo(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_loginLog_count->setText("共"+QString::number(total)+"条");
}

void LoginLogManager::initTable()
{
    ui->tableWidget_loginLog->setSortingEnabled(0);
    ui->tableWidget_loginLog->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_loginLog->clear();
    QStringList columnHeader;
    columnHeader << "访问编号" << "用户名称" << "登录地址" << "登录地点" << "浏览器" << "操作系统" << "登录状态" << "操作信息" << "登录日期";
    ui->tableWidget_loginLog->setColumnCount(columnHeader.size());
    ui->tableWidget_loginLog->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_loginLog->setRowCount(logList.size());
    ui->tableWidget_loginLog->setColumnWidth(8,150);
    for(int i = 0;i< logList.size();i++){
        ui->tableWidget_loginLog->setRowHeight(i,38);
        QString id = QString::number(logList.at(i).infoId);
        ui->tableWidget_loginLog->setItem(i,0,new QTableWidgetItem(id));
        ui->tableWidget_loginLog->setItem(i,1,new QTableWidgetItem(logList.at(i).userName));
        ui->tableWidget_loginLog->setItem(i,2,new QTableWidgetItem(logList.at(i).ipaddr));
        ui->tableWidget_loginLog->setItem(i,3,new QTableWidgetItem(logList.at(i).loginLocation));
        ui->tableWidget_loginLog->setItem(i,4,new QTableWidgetItem(logList.at(i).browser));
        ui->tableWidget_loginLog->setItem(i,5,new QTableWidgetItem(logList.at(i).os));

        QLabel *type = new QLabel();
        type->setAlignment(Qt::AlignCenter);
        for (int j= 0; j < sys_common_status.size(); ++j) {
            if(logList.at(i).status == sys_common_status.at(j).dictValue){
                type->setText(sys_common_status.at(j).dictLabel);
                type->setStyleSheet(utils.backShowStyle[sys_common_status.at(j).listClass]);
                break;
            }
        }
        type->setFixedSize(60,20);
        QWidget *widgetType = new QWidget();
        QHBoxLayout* hLayoutType = new QHBoxLayout(widgetType);
        type->setAlignment(Qt::AlignCenter);
        hLayoutType->addWidget(type);
        ui->tableWidget_loginLog->setCellWidget(i,6,widgetType);

        ui->tableWidget_loginLog->setItem(i,7,new QTableWidgetItem(logList.at(i).msg));
        ui->tableWidget_loginLog->setItem(i,8,new QTableWidgetItem(logList.at(i).loginTime));
    }
    ui->tableWidget_loginLog->setColumnWidth(6,85);
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_loginLog->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_loginLog->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_loginLog->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_loginLog->setSortingEnabled(1);
}

void LoginLogManager::initPageInfo()
{
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_loginLog_count->setText("共"+QString::number(total)+"条");
    if(currentPage == 1){
        ui->btn_loginLog_pervious->setEnabled(0);
    }else{
        ui->btn_loginLog_pervious->setEnabled(1);
    }
    ui->label_loginLog_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_loginLog_next->setEnabled(0);
    }else{
        ui->btn_loginLog_next->setEnabled(1);
    }
}
